<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改' " :close-on-click-modal='false'
             :close-on-press-escape='false' :fullscreen='true'>
    <el-form  :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter.native="dataFormSubmitHandle()"
             label-width="120px">
      <el-form-item prop="username" label="用户名">
        <el-input v-model="dataForm.username" placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item prop="deptName" label="所属部门" class="dept-list">
        <el-popover v-model:visible="deptListVisible"  placement="bottom-start"  trigger="click">
          <template #reference>
            <el-input v-model="dataForm.deptName"  :readonly="true"
                      placeholder="所属部门"></el-input>
          </template>
          <el-tree
              :data="deptList"
              :props="{ label: 'name', children: 'children' }"
              node-key="id"
              ref="deptListTree"
              :highlight-current="true"
              :expand-on-click-node="false"
              accordion
              @current-change="deptListTreeCurrentChangeHandle">
          </el-tree>
        </el-popover>

      </el-form-item>
      <el-form-item prop="password" label="密码" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.password" type="password" placeholder="密码"></el-input>
      </el-form-item>
      <el-form-item prop="comfirmPassword" label="确认密码" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.comfirmPassword" type="password"
                  placeholder="确认密码"></el-input>
      </el-form-item>
      <el-form-item prop="realName" label="真实姓名">
        <el-input v-model="dataForm.realName" placeholder="真实姓名"></el-input>
      </el-form-item>
      <el-form-item prop="gender" label="性别" size="mini">
        <el-radio-group v-model="dataForm.gender">
          <el-radio label="0">男</el-radio>
          <el-radio label="1">女</el-radio>
          <el-radio label="2">保密</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="email" label="email">
        <el-input v-model="dataForm.email" placeholder="email"></el-input>
      </el-form-item>
      <el-form-item prop="mobile" label="手机号">
        <el-input v-model="dataForm.mobile" placeholder="手机号"></el-input>
      </el-form-item>
      <el-form-item prop="roleIdList" label="角色配置" class="role-list">
        <el-select v-model="dataForm.roleIdList" multiple placeholder="角色配置">
          <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="status" label="状态" size="mini">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">停用</el-radio>
          <el-radio :label="1">正常</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {ref, reactive, onMounted, nextTick, computed} from 'vue';
import {validEmail, isMobile} from "@/utils/validate";
import {getDeptLists} from "@/network/sys/dept";
import {getUserById,putUser,postUser} from "@/network/sys/user"
import {ElMessage} from 'element-plus'
import {getRoles} from "@/network/sys/role";
import _ from 'lodash'


export default {
  name: "AddOrUpper",
  emits: ["refreshDataList"],
  setup(props, {emit}) {
    const visible = ref(false);
    const deptList = ref([]);
    const deptListVisible = ref(false);
    const roleList = ref([]);
    const roleIdListDefault = ref([]);
    const dataForm = ref({
      id: '',
      username: '',
      deptId: '0',
      deptName: '',
      password: '',
      comfirmPassword: '',
      realName: '',
      gender: 0,
      email: '',
      mobile: '',
      roleIdList: [],
      status: 1
    });
    const deptListTree = ref(null);

    const validatePassword = (rule, value, callback) => {
		  if (!dataForm.value.id && !/\S/.test(value)) {
			return callback(new Error('必填项不能为空'));
		  }
      callback();
    }
    const validateComfirmPassword = (rule, value, callback) => {
      if (!dataForm.value.id && !/\S/.test(value)) {
        return callback(new Error('必填项不能为空'));
      }
      if (dataForm.value.password !== value) {
        return callback(new Error('确认密码与密码输入不一致'));
      }
      callback();
    }
    const validateEmail = (rule, value, callback) => {
      if (!validEmail(value)) {
        return callback(new Error('{attr}格式错误', {'attr': '邮箱'}));
      }
      callback();
    }
    const validateMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        return callback(new Error('{attr}格式错误', {'attr': '手机号'}));
      }
      callback();
    }

    const dataRule = reactive({
      username: [
        {required: true, message: '必填项不能为空', trigger: 'blur'}
      ],
      deptName: [
        {required: true, message: '必填项不能为空', trigger: 'change'}
      ],
      password: [
        {validator: validatePassword, trigger: 'blur'}
      ],
      comfirmPassword: [
        {validator: validateComfirmPassword, trigger: 'blur'}
      ],
      realName: [
        {required: true, message: '必填项不能为空', trigger: 'blur'}
      ],
      email: [
        {required: true, message: '必填项不能为空', trigger: 'blur'},
        {validator: validateEmail, trigger: 'blur'}
      ],
      mobile: [
        {required: true, message: '必填项不能为空', trigger: 'blur'},
        {validator: validateMobile, trigger: 'blur'}
      ]
    })

    const dataFormRef = ref(null)

    const init = () => {
      visible.value = true;
      nextTick(function () {
        dataFormRef.value.resetFields();
        roleIdListDefault.value = [];
        Promise.all([
          getDeptList(),
          getRoleList()
        ]).then(function () {
          if (dataForm.value.id) {
            getInfo();
          }
        })
      })
    }

    // 获取部门列表
    const getDeptList = () => {
      return getDeptLists().then(function (res) {
        if (res.code !== 0) {
          return ElMessage.error(res.msg);
        }
        deptList.value = res.data;
      }).catch(function () {
      });
    }
    // 获取角色列表
    const getRoleList = () => {
      return getRoles().then(function (res) {
        if (res.code !== 0) {
          return ElMessage.error(res.msg);
        }
        roleList.value = res.data;
      }).catch(function () {
      });
    }
    // 获取信息
    const getInfo = () => {

      getUserById(dataForm.value.id).then(function (res) {
        if (res.code !== 0) {
          return ElMessage.error(res.msg);
        }
        dataForm.value = _.assignIn({}, dataForm.value, res.data);
        dataForm.value.roleIdList = [];
        deptListTree.value.setCurrentKey(dataForm.value.deptId);
        // 角色配置, 区分是否为默认角色
        for (let i = 0; i < res.data.roleIdList.length; i++) {
          if (roleList.value.filter(function (item) {
            return item.id === res.data.roleIdList[i];
          })[0]) {
            dataForm.value.roleIdList.push(res.data.roleIdList[i]);
            continue;
          }
          roleIdListDefault.push(res.data.roleIdList[i]);
        }
      }).catch((err) =>{
      });
    }
    // 所属部门树, 选中
    const deptListTreeCurrentChangeHandle = (data, node) => {
      dataForm.value.deptId = data.id;
      dataForm.value.deptName = data.name;
      deptListVisible.value = false;
    }
    // 表单提交
    const dataFormSubmitHandle = _.debounce(() => {
      dataFormRef.value.validate(function (valid) {
        if (!valid) {
          return false;
        }

        let qing = ()=> {
          return !dataForm.value.id ?  postUser(dataForm.value) : putUser(dataForm.value)
        }
        qing().then(function (res) {
          if (res.code !== 0) {
            return ElMessage.error(res.msg);
          }
          ElMessage({
            message: '操作成功',
            type: 'success',
            duration: 500,
            onClose: function () {
              visible.value = false
              emit('refreshDataList')
            }
          })
        }).catch(function () {
        });

      })
    }, 1000, {'leading': true, 'trailing': false})

    return {
      visible,
      deptList,
      deptListVisible,
      roleList,
      roleIdListDefault,
      dataForm,
      dataRule,
      validatePassword,
      validateComfirmPassword,
      validateEmail,
      validateMobile,
      init,
      getDeptList,
      getRoleList,
      getInfo,
      deptListTreeCurrentChangeHandle,
      dataFormSubmitHandle,
      deptListTree,
      dataFormRef

    }
  },

  beforeCreate: function () {
    self = this;
  },

}
</script>

<style scoped>

</style>
